﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Ink;
using System.Drawing;

namespace DentistApplication
{
    
    /// <summary>
    /// Interaction logic for PF_NewVisit.xaml
    /// </summary>
    public partial class PF_NewVisit : Window
    {
        String[] months = { "styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień" };
       

        int patientId;
        Patient currentPatient = new Patient();
        List<int> teeth = new List<int>();
        List<Recognition> currentRecognitions = new List<Recognition>();
        List<Service> currentServices = new List<Service>();
        System.Windows.Media.Brush boarder = new SolidColorBrush(Colors.Blue);
        System.Windows.Media.Brush noBoarder;
        DrawingAttributes inkAttributes;

        List<Recognition> tempRecognition = new List<Recognition>();
        int selectedRibbon = 0;
        const int VISITDETAILS_RIBBON = 0;
        const int TEETHDIAGRAM_RIBBON = 1;
        const int VISITDESCRIPTION_RIBBON = 2;

        public PF_NewVisit(int patientId)
        {
            InitializeComponent();
            this.patientId = patientId;
            currentPatient =  DatabaseHandler.getPatient(patientId);
            this.teeth_controller.EditingMode = InkCanvasEditingMode.Ink;
            inkAttributes = new DrawingAttributes { Color=Colors.Blue, Height = 10, Width = 10 };
            teeth_controller.DefaultDrawingAttributes = inkAttributes;
            boarder.Opacity = 0.25;
                   

            noBoarder = teeth_11.Background;
            fillTeethStateList();
            fill_historyTreatment();

            la_nameLastname.Content = currentPatient.firstname + " " + currentPatient.lastname;
            la_patientId.Content = "Nr kartoteki: " + currentPatient.id;

            selectedRibbon = VISITDETAILS_RIBBON;
            editTeethDiagramItems(Visibility.Hidden);
            newVisitItems(Visibility.Visible);                 
        }
               

        private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        public void addPointToDiagram(double x, double y, string color)
        {
            inkAttributes.Color = Colors.Red;

            
            // create a new Strokes collection
            StylusPointCollection stylusPoints = new StylusPointCollection();
            // Add the StylusPoints that have come in since the 
            System.Windows.Point pt = new System.Windows.Point(x, y);
            stylusPoints.Add(new StylusPoint(pt.X, pt.Y));

            // Create a stroke and add it to the InkPresenter.
            Stroke stroke = new Stroke(stylusPoints, inkAttributes);
            teeth_controller.Strokes.Add(stroke);
        }

        public void dodajZabieg(double x, double y)
        {
            list_addedItemsToDiagramTeeth.Items.Add("Dzis: " + "typ zabiegu: " + DatabaseHandler.getRecognitionType(zabiegId).name + " Ząb:" + clickedTeeth);

        }


        private void teeth_controller_StrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e)
        {
            try
            {
                teeth_controller.DefaultDrawingAttributes = inkAttributes;
                MemoryStream memoryStream = new MemoryStream();

                this.teeth_controller.Strokes.Save(memoryStream);

                memoryStream.Flush();
                Canvas.SetZIndex(teeth_controller, 0);

                
                Stroke s = teeth_controller.Strokes.Last();

                List<StylusPoint> pp = s.StylusPoints.ToList();

                StylusPoint ss = pp.First();

                double x = ss.X;
                double y = ss.Y;
                dodajZabieg(x, y);

            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, Title);
            }
        }

        private void teeth_controller_StrokeErased(object sender, RoutedEventArgs e)
        {
           
        }

        private void teeth_controller_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Point p = e.GetPosition(teeth_controller);
        }

        string clickedTeeth = "";
        private void teeth_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Label l = (Label)sender;
            clickedTeeth = l.Tag.ToString();

            switch (selectedRibbon){
                case VISITDETAILS_RIBBON:

                    if (selectedRibbon == VISITDETAILS_RIBBON)
                    {
                        if (addColumnToGrid(l.Tag.ToString()))
                            l.Background = boarder;
                        else
                            l.Background = noBoarder;
                    }
                break;

                case TEETHDIAGRAM_RIBBON:
                    Canvas.SetZIndex(teeth_controller, 10);

                break;

                case VISITDESCRIPTION_RIBBON:
                break;
            }
        }

        public bool addColumnToGrid(string header)
        {
            foreach(DataGridTextColumn c in grid_chosenTeeth.Columns)
            {
                if (c.Header.ToString().Equals(header))
                {

                    grid_chosenTeeth.Columns.Remove(c);
                    return false;
                }
            }
            grid_chosenTeeth.Columns.Add(new DataGridTextColumn { Header = header, IsReadOnly = true });
            return true;
        }

        private void bt_newTreatment_Click(object sender, RoutedEventArgs e)
        {
            int i = test.SelectedIndex;  
            List<string> chosen_teeth = new List<string>();
             foreach(DataGridTextColumn c in grid_chosenTeeth.Columns)
                chosen_teeth.Add(c.Header.ToString());

            NewServicesWindow tw = new NewServicesWindow(DatabaseHandler.getPatient(this.patientId), chosen_teeth);
            tw.Closed += new EventHandler(tw_Closed); 
            tw.Show();      
        }

        void tw_Closed(object sender, EventArgs e)
        {
            NewServicesWindow windowChild = (NewServicesWindow)sender;
            foreach (Service s in windowChild.ServiceList)
            currentServices.Add(s);
        }

        private void ribbonGroup_visitDetails_MouseUp(object sender, MouseButtonEventArgs e)
        {
            selectedRibbon = VISITDETAILS_RIBBON;
            editTeethDiagramItems(Visibility.Hidden);
            newVisitItems(Visibility.Visible);
        }

        private void ribbonGroup_editTeethDiagram_MouseUp(object sender, MouseButtonEventArgs e)
        {
            selectedRibbon = TEETHDIAGRAM_RIBBON;
            editTeethDiagramItems(Visibility.Visible);
            newVisitItems(Visibility.Hidden);
        }

        private void ribbonGroup_visitDescription_MouseUp(object sender, MouseButtonEventArgs e)
        {
            selectedRibbon = VISITDESCRIPTION_RIBBON;
            editTeethDiagramItems(Visibility.Hidden);
            newVisitItems(Visibility.Hidden);
        }

        public void newVisitItems(Visibility state)
        {
            teeth_controller.IsEnabled = state.Equals(Visibility.Visible) ? false : true;
            panel_newVisitChosenTeeth.Visibility = state;
            la_list_historyTreatment.Visibility = state;
            list_historyTreatment.Visibility = state;
        }

        private void fill_historyTreatment()
        {
            List<Service> listOfServices = DatabaseHandler.getPatientsAllServices(patientId);

            listOfServices.Add(new Service { id = 0, tooth = 12, Service_type = new Service_type { type_name="prochnica" }, Visit = new Visit { id = 0, date = DateTime.Now } });

            list_historyTreatment.Items.Clear();

            listOfServices.ForEach(s => list_historyTreatment.Items.Add(s.id_visit + ") data: " + s.Visit.date.Day + " " +
                months[s.Visit.date.Month - 1] + ", typ zabiegu: " + s.Service_type.type_name + " Ząb:" + s.tooth));
        }

        public void editTeethDiagramItems(Visibility state)
        {
            teeth_controller.IsEnabled = state.Equals(Visibility.Visible) ? true : false;
            list_teethState.Visibility = state;
            list_addedItemsToDiagramTeeth.Visibility = state;
            la_list_addedItemsToDiagramTeeth.Visibility = state;
            panel_teethdiagramLegend.Visibility = state;
        }

        System.Windows.Media.BrushConverter bc = new System.Windows.Media.BrushConverter();
     
        public void fillTeethStateList()
        {
            List<Recognition_type> allRecognitionTypes = DatabaseHandler.getAllRecognitionTypes();
          
            foreach (Recognition_type tr in allRecognitionTypes)
            {
                StackPanel st = new StackPanel { Orientation = Orientation.Horizontal };
                
                Label ll = new Label { Background = (System.Windows.Media.Brush)bc.ConvertFromString(tr.color), Height = 20, Width = 20 };
               

                Label l = new Label { Content = " - " + tr.name };
                st.Children.Add(l);
                st.Children.Add(ll);
                list_teethState.Items.Add(st);
            }

        }

        int zabiegId  =0;

        /// <summary>
        /// klikniecie na zabieg
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ll_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label l = (Label)sender;
            zabiegId = Int32.Parse(l.Tag.ToString());
            System.Windows.Media.Brush s = l.Background;
            SolidColorBrush sc = (SolidColorBrush)s;
            inkAttributes.Color = sc.Color;
        }

        public void fillAddedOznaczeniaNaZebach()
        {
            
            List<Recognition> recognitionList = DatabaseHandler.getPatientRecognitions(this.patientId);

            foreach (Recognition r in recognitionList)
            {
                StackPanel st = new StackPanel {Orientation = Orientation.Horizontal };
                Label ll = new Label { Background = (System.Windows.Media.Brush)bc.ConvertFromString(r.Recognition_type.color), Height = 20, Width = 20 };
                ll.Tag = r.id;
                Label l = new Label { Content = r.id+") "+r.Recognition_type.name+" ząb: "+r.nr_tooth};
                ll.MouseDown += new MouseButtonEventHandler(ll_MouseDown);
                st.Children.Add(l);
                st.Children.Add(ll);

                list_addedItemsToDiagramTeeth.Items.Add(st);
            }
        }

        private void bt_finishVisit_Click(object sender, RoutedEventArgs e)
        {

            if (MessageBox.Show("Zapisać dane do bazy?", "Potwierdź zapis", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                Visit v = new Visit
                {
                    date = DateTime.Now,
                    id_patient = this.patientId,
                    id_personel = 1
                };

                if (DatabaseHandler.saveVisit(v, currentServices, currentRecognitions))
                {
                    MessageBox.Show("Wizyta została dodana");
                    
                }
                else
                    MessageBox.Show("Wystapił bład");    
            }

            this.Close();            
        }

        private void addNewTempRecognition()
        {
            new Recognition { };
        }
    }
}